'use strict';

const uniIdCommon = require('uni-id-common');
const db = uniCloud.database();
const dbCmd = db.command;
const { getConfig } = require('uni-config-center');
const zhentouConfig = getConfig('zhentou-config');
// const utils = require('utils'); // 临时注释避免错误

const wxpay = require('./wxpay');

/**
 * 记录积分变化（内联版本）
 * 注意：此函数应该在积分已经更新之后调用
 * balance_after 会自动查询当前最新的积分余额
 */
async function logPointChange({ userId, changeAmount, changeType, description, relatedOrderId = null }) {
  try {
    // 查询用户当前积分（此时积分已经更新过了）
    const userRes = await db.collection('users').doc(userId).field({ points: 1 }).get();
    if (!userRes.data || userRes.data.length === 0) {
      console.error(`[积分记录] 用户不存在: ${userId}`);
      return;
    }
    const currentPoints = userRes.data[0].points || 0;
    // balance_after 就是当前积分（因为积分已经更新过了）
    const balanceAfter = currentPoints;

    await db.collection('point_records').add({
      user_id: userId,
      change_amount: changeAmount,
      change_type: changeType,
      description: description,
      related_order_id: relatedOrderId,
      balance_after: balanceAfter,
      create_time: Date.now()
    });
    console.log(`[积分记录] 用户 ${userId} 积分变化: ${changeAmount > 0 ? '+' : ''}${changeAmount}, 余额: ${balanceAfter}, 原因: ${description}`);
  } catch (error) {
    console.error(`[积分记录] 记录失败:`, error);
  }
}

/**
 * 检查用户的订单状态，核减已取消订单的佣金和积分
 * @param {string} userId - 用户ID
 * @returns {object} 核查结果
 */
async function checkAndAdjustUserOrders(userId) {
  console.log(`[核查] 开始检查用户 ${userId} 的订单状态...`);
  const now = Date.now();

  // 查找用户作为推广人的所有倒计时期间的订单
  const ordersToCheck = await db.collection('orders').where({
    promoter_id: userId,
    activation_countdown: dbCmd.gt(0),
    activation_date: dbCmd.gt(now)
  }).get();

  if (ordersToCheck.data.length === 0) {
    console.log(`[核查] 用户 ${userId} 没有需要检查的订单`);
    return { checkedCount: 0, adjustedCount: 0, adjustedAmount: 0, adjustedPoints: 0 };
  }

  console.log(`[核查] 发现 ${ordersToCheck.data.length} 条倒计时中的订单`);

  // 获取access_token
  let accessToken;
  try {
    const tokenRes = await uniCloud.callFunction({
      name: 'wx-api-center',
      data: { action: 'getAccessToken' }
    });
    if (tokenRes.result.code !== 0) {
      throw new Error(tokenRes.result.message);
    }
    accessToken = tokenRes.result.accessToken;
  } catch (err) {
    console.error(`[核查] 获取access_token失败:`, err.message);
    throw new Error('无法获取微信API访问令牌');
  }

  let checkedCount = 0;
  let adjustedCount = 0;
  let adjustedAmount = 0;
  let adjustedPoints = 0;

  for (const order of ordersToCheck.data) {
    checkedCount++;
    const orderId = order._id;

    try {
      // 调用微信API获取订单最新状态
      const detailUrl = `https://api.weixin.qq.com/channels/ec/order/get?access_token=${accessToken}`;
      const detailRes = await uniCloud.httpclient.request(detailUrl, {
        method: 'POST',
        contentType: 'json',
        dataType: 'json',
        data: { order_id: orderId }
      });

      if (!detailRes.data || detailRes.data.errcode !== 0) {
        console.error(`[核查] 获取订单 ${orderId} 详情失败`);
        continue;
      }

      const wechatOrder = detailRes.data.order;
      const wechatStatus = wechatOrder.status;

      // 如果订单被取消或退款（状态码200或250）
      if ((wechatStatus === 200 || wechatStatus === 250) && order.status === 'completed') {
        console.log(`[核查] 订单 ${orderId} 已被取消/退款，开始核减...`);

        // 核减积分
        if (order.points_awarded > 0) {
          await db.collection('users').doc(userId).update({
            points: dbCmd.inc(-order.points_awarded)
          });
          adjustedPoints += order.points_awarded;
          console.log(`[核查] 已核减积分 ${order.points_awarded}`);
        }

        // 核减佣金
        if (order.commission_amount > 0) {
          if (order.commission_status === 'pending') {
            await db.collection('users').doc(userId).update({
              commission_pending: dbCmd.inc(-order.commission_amount)
            });
            adjustedAmount += order.commission_amount;
            console.log(`[核查] 已核减待激活佣金 ${order.commission_amount} 分`);
          } else if (order.commission_status === 'activated') {
            await db.collection('users').doc(userId).update({
              commission_available: dbCmd.inc(-order.commission_amount),
              commission_total: dbCmd.inc(-order.commission_amount)
            });
            adjustedAmount += order.commission_amount;
            console.log(`[核查] 已核减可提现佣金 ${order.commission_amount} 分`);
          }
        }

        // 更新订单状态
        const newStatus = wechatStatus === 200 ? 'cancelled' : 'refunded';
        await db.collection('orders').doc(orderId).update({
          status: newStatus,
          commission_status: 'cancelled',
          last_sync_time: now
        });

        adjustedCount++;
        console.log(`[核查] 订单 ${orderId} 已处理完成`);
      }

    } catch (err) {
      console.error(`[核查] 检查订单 ${orderId} 失败:`, err.message);
    }
  }

  console.log(`[核查] 完成。检查了 ${checkedCount} 条订单，调整了 ${adjustedCount} 条订单，核减佣金 ${adjustedAmount} 分，核减积分 ${adjustedPoints}`);

  return {
    checkedCount,
    adjustedCount,
    adjustedAmount,
    adjustedPoints
  };
}

exports.main = async (event, context) => {
  // 检查是否是微信异步通知请求（HTTP POST 请求）
  if (event.httpMethod === 'POST' && event.body) {
    console.log('[异步通知] 收到HTTP POST请求，可能是微信异步通知');
    console.log('[异步通知] 请求头:', JSON.stringify(event.headers || {}, null, 2));
    console.log('[异步通知] 请求体:', event.body);

    try {
      // 解析请求体
      let notificationData;
      if (typeof event.body === 'string') {
        notificationData = JSON.parse(event.body);
      } else {
        notificationData = event.body;
      }

      // 调用微信支付模块处理异步通知
      const notificationResult = await wxpay.handleTransferNotification(notificationData);
      console.log('[异步通知] 处理结果:', notificationResult);

      return notificationResult;
    } catch (e) {
      console.error('[异步通知] 处理失败:', e);
      return { code: 500, message: `处理通知失败: ${e.message}` };
    }
  }

  const { action, params } = event;
  let result = {};

  const uniIdIns = uniIdCommon.createInstance({ context });
  let payload = {};

  if (action !== 'loginByWeixin') {
    payload = await uniIdIns.checkToken(event.uniIdToken);
    if (payload.errCode) {
      return payload;
    }
  }

  switch (action) {
    case 'loginByWeixin':
      // 1. 完成登录/注册
      result = await uniIdIns.loginByWeixin(params);

      // 2. 如果登录成功，检查并保存 UnionID
      if (result.uid) {
        try {
          // 获取用户当前信息
          const userRes = await db.collection('users').doc(result.uid).get();
          const user = userRes.data[0];

          // 检查是否有 unionid（uni-id-common 可能已经保存了）
          if (result.unionid && !user.wx_unionid) {
            console.log(`为用户 ${result.uid} 保存UnionID: ${result.unionid}`);
            await db.collection('users').doc(result.uid).update({
              wx_unionid: result.unionid
            });
          }
        } catch (e) {
          console.error('保存UnionID失败', e);
        }
      }

      // 3. 如果登录成功，则更新用户昵称和头像
      if (result.uid && params.userInfo) {
        try {
          const { nickName, avatarUrl } = params.userInfo;
          const updateData = {};
          if (nickName) updateData.nickname = nickName;
          if (avatarUrl) updateData.avatar = avatarUrl;

          if (Object.keys(updateData).length > 0) {
            await db.collection('users').doc(result.uid).update(updateData);
            console.log(`用户 ${result.uid} 的个人资料已更新。`, updateData);

            // 将更新后的信息合并到返回给前端的 userInfo 中
            if (!result.userInfo) result.userInfo = {};
            Object.assign(result.userInfo, updateData);
          }
        } catch (e) {
          console.error('更新用户信息失败', e); // 更新失败不阻塞主流程
        }
      }

      // 3. 处理推荐人逻辑（支持新用户和老用户）
      if (result.uid && params.promoter_id) {
        try {
          // 获取用户当前信息
          const userRes = await db.collection('users').doc(result.uid).get();
          const user = userRes.data[0];

          // 检查用户是否已有推荐人
          if (!user.promoter_id) {
            // 用户没有推荐人，进行绑定
            await db.collection('users').doc(result.uid).update({
              promoter_id: params.promoter_id
            });
            result.promoterBinded = true;

            if (result.type === 'register') {
              console.log(`新用户 ${result.uid} 已成功绑定推荐人 ${params.promoter_id}`);
            } else {
              console.log(`老用户 ${result.uid} 已成功绑定推荐人 ${params.promoter_id}`);
            }

            // 为推荐人增加积分（新用户注册奖励）- 新逻辑：1积分/人，10积分封顶
            if (result.type === 'register') {
              // 查询推荐人当前的推广人数
              const promoterRes = await db.collection('users').doc(params.promoter_id).get();
              const promoter = promoterRes.data[0];
              const currentReferralCount = promoter.referral_count || 0;

              // 只有推广人数小于10时才增加积分
              if (currentReferralCount < 10) {
                await db.collection('users').doc(params.promoter_id).update({
                  points: dbCmd.inc(1),
                  referral_count: dbCmd.inc(1)
                });
                console.log(`已为推荐人 ${params.promoter_id} 增加 1 积分（推荐新用户，当前推广 ${currentReferralCount + 1}/10 人）`);

                // 记录积分变化
                await logPointChange({
                  userId: params.promoter_id,
                  changeAmount: 1,
                  changeType: 'referral_register',
                  description: `推荐新用户注册（第${currentReferralCount + 1}人）`
                });
              } else {
                // 只增加推广人数，不增加积分
                await db.collection('users').doc(params.promoter_id).update({
                  referral_count: dbCmd.inc(1)
                });
                console.log(`推荐人 ${params.promoter_id} 已达到推广积分上限（10积分），不再增加积分，但记录推广人数`);
              }
            } else {
              // 老用户绑定推荐人，不给积分，只记录推广人数
              await db.collection('users').doc(params.promoter_id).update({
                referral_count: dbCmd.inc(1)
              });
              console.log(`老用户绑定推荐人 ${params.promoter_id}，不给予积分奖励`);
            }

            // await utils.checkLevelUp(params.promoter_id); // 临时注释避免错误
            console.log('推荐人等级检查已跳过（临时修复）');

          } else if (user.promoter_id === params.promoter_id) {
            console.log(`用户 ${result.uid} 已绑定推荐人 ${params.promoter_id}，无需重复绑定`);
          } else {
            console.log(`用户 ${result.uid} 已有推荐人 ${user.promoter_id}，不覆盖为 ${params.promoter_id}`);
          }

        } catch (e) {
          console.error('绑定推荐人或处理积分/等级失败', e);
        }
      }

      // 4. 兼容前端，处理 avatarUrl 字段，并检查管理员权限
      if (result.userInfo) {
        if (result.userInfo.avatar) {
          result.userInfo.avatarUrl = result.userInfo.avatar;
        }
        if (Array.isArray(zhentouConfig.admin_uids) && zhentouConfig.admin_uids.includes(result.uid)) {
          result.userInfo.isAdmin = true;
        }
      }
      break;

    case 'getUserInfo':
      const userRes = await db.collection('users').doc(payload.uid).field({
        'wx_openid': false,
        'password': false
      }).get();
      
      if (userRes.data && userRes.data.length > 0) {
        const userInfo = userRes.data[0];
        
        // 兼容前端，增加 avatarUrl 字段
        if (userInfo.avatar) {
          userInfo.avatarUrl = userInfo.avatar;
        }

        if (Array.isArray(zhentouConfig.admin_uids) && zhentouConfig.admin_uids.includes(payload.uid)) {
          userInfo.isAdmin = true;
        }
        result = { code: 0, userInfo: userInfo };
      } else {
        result = { code: 404, message: '用户不存在' };
      }
      break;

    case 'generateTransferPackage': {
      // 新版本流程：生成加密的package，前端调用wx.requestMerchantTransfer()
      const { amount } = params;
      if (!amount || amount <= 0 || !Number.isInteger(amount)) {
        throw new Error('提现金额必须是正整数');
      }

      try {
        console.log(`[提现] 用户 ${payload.uid} 申请生成转账package，金额: ${amount} 分`);

        // 1. 获取用户信息并验证
        const userDoc = await db.collection('users').doc(payload.uid).get();
        const user = userDoc.data[0];

        if (!user) {
          throw new Error('用户不存在');
        }
        if ((user.commission_available || 0) < amount) {
          throw new Error(`可提现余额不足。当前余额: ${user.commission_available || 0} 分，申请提现: ${amount} 分`);
        }
        if (!user.wx_openid || !user.wx_openid.mp) {
          throw new Error('用户OpenID不存在，无法提现');
        }

        // 2. 核查订单状态
        console.log(`[提现] 开始核查订单状态...`);
        const checkResult = await checkAndAdjustUserOrders(payload.uid);
        if (checkResult.adjustedCount > 0) {
          console.log(`[提现] 核查发现 ${checkResult.adjustedCount} 条已取消订单，已核减佣金 ${checkResult.adjustedAmount} 分`);
          // 重新检查余额
          const updatedUserDoc = await db.collection('users').doc(payload.uid).get();
          const updatedUser = updatedUserDoc.data[0];
          if ((updatedUser.commission_available || 0) < amount) {
            throw new Error(`核查后可提现余额不足。当前余额: ${updatedUser.commission_available || 0} 分，申请提现: ${amount} 分`);
          }
        }

        // 3. 生成加密的package
        console.log(`[提现] 开始生成转账package...`);
        const packageData = await wxpay.generateTransferPackage({
          amount: amount,
          openid: user.wx_openid.mp
        });

        // 4. 扣除用户余额（在生成package时就扣除，确保金额被锁定）
        await db.collection('users').doc(payload.uid).update({
          commission_available: dbCmd.inc(-amount)
        });
        console.log(`[提现] 已扣除用户余额 ${amount} 分`);

        // 5. 创建待处理的提现记录（状态为pending_user_confirm）
        const withdrawalRes = await db.collection('withdrawals').add({
          user_id: payload.uid,
          amount: amount,
          out_bill_no: packageData.outBillNo,  // 新版本API使用out_bill_no
          status: 'pending_user_confirm',  // 等待用户在微信官方页面确认
          create_date: Date.now(),
          package_generated_time: Date.now()
        });
        console.log(`[提现] 已创建待处理提现记录: ${withdrawalRes.id}`);

        // 6. 返回package给前端
        result = {
          code: 0,
          message: '转账package生成成功',
          data: {
            mchId: packageData.mchId,
            appId: packageData.appId,
            package: packageData.package,
            outBillNo: packageData.outBillNo,  // 新版本API使用out_bill_no
            withdrawalId: withdrawalRes.id
          }
        };

        console.log(`[提现] Package生成成功，已扣除余额，等待用户确认`);

      } catch (e) {
        console.error(`[提现] 生成package失败:`, e);
        result = { code: 500, message: `生成package失败: ${e.message}` };
      }
      break;
    }

    case 'withdraw': {
      // 旧版本流程（已弃用，保留用于兼容）
      const { amount } = params;
      if (!amount || amount <= 0 || !Number.isInteger(amount)) {
        throw new Error('提现金额必须是正整数');
      }

      let withdrawalId;

      try {
        // 提现前先核查订单状态，确保没有已取消的订单
        console.log(`[提现] 用户 ${payload.uid} 申请提现 ${amount} 分，开始核查订单状态...`);
        const checkResult = await checkAndAdjustUserOrders(payload.uid);

        if (checkResult.adjustedCount > 0) {
          console.log(`[提现] 核查发现 ${checkResult.adjustedCount} 条已取消订单，已核减佣金 ${checkResult.adjustedAmount} 分，积分 ${checkResult.adjustedPoints}`);
        }

        // 1. 获取用户信息并验证
        const userDoc = await db.collection('users').doc(payload.uid).get();
        const user = userDoc.data[0];

        if (!user) {
          throw new Error('用户不存在');
        }
        if ((user.commission_available || 0) < amount) {
          throw new Error(`可提现余额不足。当前余额: ${user.commission_available || 0} 分，申请提现: ${amount} 分`);
        }
        if (!user.wx_openid || !user.wx_openid.mp) {
          throw new Error('用户OpenID不存在，无法提现');
        }

        // 2. 扣除用户余额
        await db.collection('users').doc(payload.uid).update({
          commission_available: dbCmd.inc(-amount)
        });
        console.log(`[提现] 已扣除用户余额 ${amount} 分`);

        // 3. 创建处理中的提现记录
        const withdrawalRes = await db.collection('withdrawals').add({
          user_id: payload.uid,
          amount: amount,
          status: 'processing',
          create_date: Date.now(),
        });
        withdrawalId = withdrawalRes.id;
        console.log(`[提现] 已创建提现记录 ${withdrawalId}`);

        // 4. 执行微信支付转账
        console.log(`[提现] 开始调用微信支付转账接口...`);
        console.log(`[提现] 转账参数:`, { amount, openid: user.wx_openid.mp });

        const transferResult = await wxpay.transferToBalance({
            amount: amount,
            openid: user.wx_openid.mp
        });
        console.log(`[提现] 微信支付转账成功:`, transferResult);

        // 5. 更新提现记录为成功
        await db.collection('withdrawals').doc(withdrawalId).update({
            status: 'success',
            transaction_id: transferResult.out_batch_no // 使用微信的批次号作为ID
        });
        console.log(`[提现] 提现记录已更新为成功状态`);

        result = { code: 0, message: '提现成功' };

      } catch (e) {
        console.error(`[提现] 提现失败:`, e);

        // 如果发生任何错误，回滚金额
        if (withdrawalId) {
            console.log(`[提现] 开始回滚操作...`);
            await db.collection('withdrawals').doc(withdrawalId).update({
                status: 'failed',
                error_message: e.message
            });
            await db.collection('users').doc(payload.uid).update({
                commission_available: dbCmd.inc(amount)
            });
            console.log(`[提现] 回滚完成，已退回 ${amount} 分到用户余额`);
        }
        result = { code: 500, message: `提现失败: ${e.message}` };
      }
      break;
    }

    case 'handleTransferNotification': {
      // 处理微信异步通知（不需要用户认证）
      try {
        console.log(`[异步通知] 收到微信转账通知`);
        const notificationData = params;

        const notificationResult = await wxpay.handleTransferNotification(notificationData);
        result = notificationResult;

      } catch (e) {
        console.error(`[异步通知] 处理失败:`, e);
        result = { code: 500, message: `处理通知失败: ${e.message}` };
      }
      break;
    }

    case 'queryWithdrawalStatus': {
      // 查询提现状态（用户可以手动查询最新状态）
      try {
        console.log(`[查询] 用户 ${payload.uid} 查询提现状态`);

        // 查询用户最近的提现记录
        const withdrawalQuery = await db.collection('withdrawals')
          .where({ user_id: payload.uid })
          .orderBy('create_date', 'desc')
          .limit(1)
          .get();

        if (withdrawalQuery.data.length === 0) {
          result = {
            code: 0,
            message: '暂无提现记录',
            data: null
          };
        } else {
          const withdrawal = withdrawalQuery.data[0];
          console.log(`[查询] 找到提现记录:`, {
            id: withdrawal._id,
            status: withdrawal.status,
            amount: withdrawal.amount,
            create_date: withdrawal.create_date
          });

          result = {
            code: 0,
            message: '查询成功',
            data: {
              id: withdrawal._id,
              amount: withdrawal.amount,
              status: withdrawal.status,
              create_date: withdrawal.create_date,
              finish_time: withdrawal.finish_time,
              error_message: withdrawal.error_message,
              // 状态说明
              statusText: {
                'pending_user_confirm': '等待用户确认',
                'pending_transfer': '等待转账处理',
                'success': '转账成功',
                'failed': '转账失败'
              }[withdrawal.status] || '未知状态'
            }
          };
        }

      } catch (e) {
        console.error(`[查询] 查询失败:`, e);
        result = { code: 500, message: `查询失败: ${e.message}` };
      }
      break;
    }

    case 'getPointRecords': {
      // 查询积分明细
      try {
        const { page = 1, pageSize = 20 } = params || {};
        const skip = (page - 1) * pageSize;

        // 查询用户的积分记录
        const recordsRes = await db.collection('point_records')
          .where({
            user_id: payload.uid
          })
          .orderBy('create_time', 'desc')
          .skip(skip)
          .limit(pageSize)
          .get();

        // 查询总数
        const countRes = await db.collection('point_records')
          .where({
            user_id: payload.uid
          })
          .count();

        result = {
          code: 0,
          message: '查询成功',
          data: {
            records: recordsRes.data,
            total: countRes.total,
            page: page,
            pageSize: pageSize,
            hasMore: skip + recordsRes.data.length < countRes.total
          }
        };
      } catch (e) {
        console.error('[积分明细] 查询失败:', e);
        result = {
          code: 500,
          message: `查询失败: ${e.message}`
        };
      }
      break;
    }

    case 'checkOrdersBeforeUpgrade': {
      // 升级前核查订单状态
      try {
        console.log(`[升级核查] 用户 ${payload.uid} 准备升级，开始核查订单状态...`);
        const checkResult = await checkAndAdjustUserOrders(payload.uid);

        result = {
          code: 0,
          message: '核查完成',
          data: {
            checkedCount: checkResult.checkedCount,
            adjustedCount: checkResult.adjustedCount,
            adjustedAmount: checkResult.adjustedAmount,
            adjustedPoints: checkResult.adjustedPoints
          }
        };

        if (checkResult.adjustedCount > 0) {
          result.message = `发现 ${checkResult.adjustedCount} 条已取消订单，已核减佣金 ${checkResult.adjustedAmount} 分，积分 ${checkResult.adjustedPoints}`;
        }

      } catch (e) {
        result = { code: 500, message: `核查失败: ${e.message}` };
      }
      break;
    }

    case 'getMySharingUsers':
      try {
        console.log(`[获取分享用户] 用户 ${payload.uid} 请求获取其推广的用户列表`);

        // 1. 获取当前用户推广的所有用户
        const sharingUsersRes = await db.collection('users')
          .where({
            promoter_id: payload.uid
          })
          .field({
            '_id': true,
            'nickname': true,
            'avatar': true,
            'avatarUrl': true,
            'register_date': true,  // uni-id-common 使用 register_date
            'level': true
          })
          .orderBy('register_date', 'desc')
          .get();

        const sharingUsers = sharingUsersRes.data || [];
        console.log(`[获取分享用户] 找到 ${sharingUsers.length} 个推广用户`);

        // 2. 为每个用户检查是否购买过商品
        const usersWithPurchaseInfo = [];
        let totalPurchasedUsers = 0;
        let totalCommission = 0;

        for (const user of sharingUsers) {
          // 检查用户是否有订单（不限制状态，只要有佣金就算已购买）
          // 包括 pending（待激活）和 activated（已激活）状态的订单
          const ordersRes = await db.collection('orders')
            .where({
              buyer_id: user._id,
              commission_amount: dbCmd.gt(0)  // 有佣金的订单
            })
            .field({
              'commission_amount': true,
              'commission_status': true,
              'status': true
            })
            .get();

          const orders = ordersRes.data || [];
          const hasPurchased = orders.length > 0;

          // 计算该用户带来的总佣金（只计算已激活的佣金）
          let userTotalCommission = 0;
          for (const order of orders) {
            if (order.commission_status === 'activated' && order.commission_amount) {
              userTotalCommission += order.commission_amount;
            }
          }

          if (hasPurchased) {
            totalPurchasedUsers++;
          }
          totalCommission += userTotalCommission;

          usersWithPurchaseInfo.push({
            ...user,
            hasPurchased,
            totalCommission: userTotalCommission,
            purchaseCount: orders.length,
            registerTime: user.register_date || null  // 添加注册时间字段
          });
        }

        console.log(`[获取分享用户] 其中 ${totalPurchasedUsers} 个用户已购买，总佣金: ${totalCommission} 分`);

        result = {
          code: 0,
          data: usersWithPurchaseInfo,
          total: usersWithPurchaseInfo.length,
          summary: {
            totalUsers: usersWithPurchaseInfo.length,
            purchasedUsers: totalPurchasedUsers,
            totalCommission: totalCommission
          }
        };

      } catch (error) {
        console.error('[获取分享用户] 错误:', error);
        result = {
          code: 500,
          message: `获取分享用户失败: ${error.message}`
        };
      }
      break;

    default:
      result = {
        code: 403,
        message: '请求不受支持',
      };
      break;
  }

  return result;
};